package com.theexceptions.todo.view;

import com.theexceptions.todo.controller.Controller;
import com.theexceptions.todo.controller.LoginController;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

/**
 * An activity that manages user login. Corresponds to the view: login.xml.
 * 
 * @author TheExceptions
 */
public class LoginActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Set context view to login
		setContentView(R.layout.login);

		// Give controllers a context
		Controller.setContext(this.getApplicationContext());
	}

	/**
	 * Checks the values from the username and password fields and attempts to
	 * log the user into the system.
	 * 
	 * @param view Current view
	 */
	public boolean loginButtonClicked(View view) {
		/*
		 * JUnit tested
		 */

		EditText editTextUsername = (EditText) this.findViewById(R.id.editTextUsername);
		EditText editTextPassword = (EditText) this.findViewById(R.id.editTextPassword);
		String username = editTextUsername.getText().toString();
		String password = editTextPassword.getText().toString();

		int result = LoginController.loginUser(username, password);

		if (result == LoginController.LOGIN_SUCCESS) {
			Toast.makeText(this, "Login successful.", Toast.LENGTH_SHORT).show();
			editTextUsername.setText("");
			editTextPassword.setText("");

			Intent intent = new Intent(findViewById(android.R.id.content).getContext(), TasksActivity.class);
			startActivity(intent);
			return true;
		} else if (result == LoginController.INVALID_USERNAME) {
			Toast.makeText(this, "Username not found.", Toast.LENGTH_SHORT).show();
		} else if (result == LoginController.WRONG_PASSWORD) {
			Toast.makeText(this, "Password is incorrect.", Toast.LENGTH_SHORT).show();
		}

		return false;
	}

	/**
	 * Switches the layout from the login screen to the register screen when
	 * "create new user" is pressed
	 * 
	 * @param view Current view
	 */
	public void createUserButtonClicked(View view) {
		// Move to register activity screen
		Intent intent = new Intent(view.getContext(), RegisterActivity.class);
		startActivity(intent);
	}

	/**
	 * Switches the application to the home screen activity.
	 */
	private void goToHomeScreen() {

	}
}
